<template>
  <div class="container with-nav-padding">
    <div
      @click="$router.push({ path: '/addr-mng', query: { source: 'payment' } })"
      class="addr-panel"
    >
      <div class="addr-icon"></div>
      <div v-if="!Object.keys(paymentAddr).length" class="addr">
        请添加联系人
      </div>
      <div v-else class="addr-info">
        <div class="user">
          <span class="name">{{ paymentAddr.realname }}</span>
          <span class="tel">{{ paymentAddr.mobile }}</span>
        </div>
        <div class="addr-detail">
          {{ paymentAddr.city_str }} {{ paymentAddr.detail }}
        </div>
      </div>
      <div class="right-btn"></div>
    </div>
    <div
      v-if="goodList[0] && goodList[0].commodity.is_serve === 1"
      @click="$router.push({ path: '/service-time' })"
      class="service-panel"
    >
      <div class="addr">
        选择服务时间
      </div>
      <div v-if="serviceTime" class="time-info">{{ serviceTimeText() }}</div>
      <div class="right-btn"></div>
    </div>
    <div v-for="(item, index) in goodList" :key="index" class="item-panel">
      <div class="item-info">
        <div class="left">
          <img :src="item.commodity.spec_img" alt="" />
        </div>
        <div class="middle">
          <div class="item-name">
            {{ item.commodity.name }}
          </div>
          <div class="item-size">规格：{{ item.commodity.specname }}</div>
        </div>
        <div class="right">
          <div class="price">¥ {{ item.commodity.spe_price }}</div>
        </div>
      </div>
      <div class="item-cell">
        <div class="header">购买数量</div>
        <yd-spinner
          style="margin-top:0.4rem"
          width="3.2rem"
          height="1rem"
          v-model="item.commodity.number"
        ></yd-spinner>
      </div>
      <div v-if="item.commodity.is_points === 1" class="item-cell">
        <div class="header">花费积分</div>
        <div class="postage">
          {{ -(-item.commodity.points) * item.commodity.number | pointFix}}积分
        </div>
      </div>
      <div class="item-cell" v-if="showDiscount(goodList, index)">
        <div class="header">优惠券</div>
        <div
          v-if="
            (item.coupon && !item.coupon.length) || item.commodity.is_vip === 1
          "
          class="coupon-text"
        >
          目前暂无可用优惠券
        </div>
        <div v-else @click="toCouponChoose(item)" class="coupon-text">
          {{ couponStr(item, index) }}
        </div>
      </div>
      <div class="item-cell" v-if="showDiscount(goodList, index)">
        <div class="header">运费</div>
        <div class="postage">￥{{ item.commodity.freight }}</div>
      </div>
      <div
        v-if="
          (item.commodity.discount_price !== 0 ||
            item.commodity.is_vip === 1) &&
            item.commodity.is_points !== 1 &&
            vip_rule !== 0
        "
        class="item-cell"
      >
        <div class="header">会员价 <span class="vip-tag">VIP</span></div>
        <div class="vip-price">
          <div>￥{{ item.commodity.discount_price }}</div>
          <button @click="$router.push('/vip')" v-if="isVip === 0 && vip_rule !== 0">
            购买会员
          </button>
        </div>
      </div>
      <div
        v-if="index === goodList.length - 1"
        class="item-cell with-grey-bottom-border"
      >
        <div class="header">备注</div>
        <input
          v-model="remark"
          type="text"
          placeholder="如有特殊需求，请给商家留言"
        />
      </div>
      <div class="item-cell">
        <div class="header"></div>
        <div class="total">
          共{{item.commodity.number}}件 小计：<span class="price">¥{{ totalPrice(item) }}</span>
        </div>
      </div>
    </div>
    <div v-if="hasVipGiftBag" class="protocol">
      <button @click="agree = !agree" :class="{ active: agree }"></button>
      我的同意
      <span class="protocol-name" @click="$router.push('/vip-protocol')"
        >会员协议内容</span
      >
    </div>
    
    <div v-if="hasVipGiftBag && (!identity_e || !identity_v)" class="id-card">
      <div class="title">
        请上传身份证照片
      </div>
      <div class="card-img">
        <div class="card-cell">
          <div v-if="!imgFront">
            <label for="vip-card-front">
              <img src="@/assets/实名认证/sfz2.png" alt="" />
            </label>
            身份照正面
          </div>
          <img @click="imgFront = null" v-else :src="imgFront" alt="" />
        </div>
        <div class="card-cell">
          <div v-if="!imgBack">
            <label for="vip-card-back">
              <img src="@/assets/实名认证/sfz1.png" alt="" />
            </label>
            身份照背面
          </div>
          <img @click="imgBack = null" v-else :src="imgBack" alt="" />
        </div>
        <input
          id="vip-card-front"
          @change="frontChange($event)"
          type="file"
          style="position:absolute; clip:rect(0 0 0 0);"
          accept="image/*"
        />
        <input
          id="vip-card-back"
          @change="backChange($event)"
          type="file"
          style="position:absolute; clip:rect(0 0 0 0);"
          accept="image/*"
        />
      </div>
    </div>
    <div class="bottom-bar">
      <span class="text"
        >共{{ goodList.length }}件, 合计：<span class="price"
          >¥{{ orderTotalPrice() }}</span
        ></span
      >
      <button class="submit" @click="orderSubmit" :style="{background: mainColor}">提交订单</button>
    </div>
    <payment-mask
      :orderInfo="orderInfo"
      v-if="showPaymentMask"
      :goodList="goodList"
      @panelClose="showPaymentMask = false"
    ></payment-mask>
  </div>
</template>

<script>
import { toPayment, orderSubmit } from "@/api/mall";
import paymentMask from "./component/payment-mask.vue";
import { mapState, mapActions, mapMutations } from "vuex";
import { fileUpload } from "@/api/file";
import { profileEdit } from "@/api/profile";
import moment from "moment";
import wx from "weixin-js-sdk";
moment.locale("zh-cn");
export default {
  data() {
    return {
      number: 1,
      hasVipPrice: true,
      isVip: 0,
      showPaymentMask: false,
      goodList: [],
      remark: "",
      orderInfo: {},
      agree: false,
      hasVipGiftBag: false,
      cart: "",
      userPoints: 0,
      imgFront: null,
      imgBack: null,
      identity_e: "",
      identity_v: "",
      usedCp: null
    };
  },
  computed: {
    ...mapState({
      paymentCouponList: state => state.coupon.paymentCouponList,
      paymentAddr: state => state.address.paymentAddr,
      serviceTime: state => state.address.serviceTime,
       mainColor: state => state.app.mainColor,
      subColor: state => state.app.subColor,
      vip_rule: state => state.app.vip_rule
    })
  },
  methods: {
    showDiscount(list, index) {
      if (this.$route.query.type == 'cart' && list.length > 1 && index !== list.length - 1) {
        return false
      } else if (this.$route.query.isSpell) {
        return false
      } else {
        return true
      }
    },
    ...mapActions(["couponMarking"]),
    ...mapMutations([
      "setCurrentCoupon",
      "setCurrentSpec_id",
      "clearCoupon",
      "clearAddr",
      "setAddr",
      "clearTime"
    ]),
    identityUpdate() {
      profileEdit({
        identity_e: this.imgFront,
        identity_v: this.imgBack
      }).then(res => {
        if (res.status === 200) {
          // this.identity_e = this.imgFront;
          // this.identity_v = this.imgBack;
        }
      });
    },
    frontChange(e) {
      // console.log(e)
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      fileUpload(formData).then(res => {
        if (res.status === 200) {
          this.imgFront = res.data.data.file;
          if (this.imgFront && this.imgBack) this.identityUpdate();
        }
      });
    },
    backChange(e) {
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      fileUpload(formData).then(res => {
        if (res.status === 200) {
          this.imgBack = res.data.data.file;
          if (this.imgFront && this.imgBack) this.identityUpdate();
        }
      });
    },
    serviceTimeText() {
      return `${moment(this.serviceTime).format("MM-DD")}(${moment(
        this.serviceTime
      ).format("ddd")})${moment(this.serviceTime).format("HH:mm")}`;
    },
    toCouponChoose(item) {
      this.setCurrentCoupon(item.coupon);
      this.setCurrentSpec_id(item.commodity.spu_id);
      this.$router.push({
        path: "/my-coupon",
        query: { from: "payment" }
      });
    },
    orderSubmit() {
      if (this.hasVipGiftBag === true && this.agree !== true) {
        this.$dialog.toast({
          mes: "未同意会员协议",
          timeout: 1500,
          icon: "error"
        });
        return;
      }
      if (
        this.hasVipGiftBag &&
        (!this.identity_e || !this.identity_v) &&
        (!this.imgFront || !this.imgBack)
      ) {
        this.$dialog.toast({
          mes: "请先上传身份证照片",
          timeout: 1500,
          icon: "error"
        });
        return;
      }
      if (!Object.keys(this.paymentAddr).length) {
        this.$dialog.toast({
          mes: "请选择地址",
          timeout: 1500,
          icon: "error"
        });
        return;
      }
      //判断订单积分是否足够
      let pointCost = 0;
      this.goodList.forEach(item => {
        if (item.commodity.is_points === 1) {
          pointCost -= -item.commodity.points;
        }
      });
      if (-pointCost < -this.userPoints) {
        this.$dialog.toast({
          mes: "用户积分不足",
          icon: "error"
        });
        return;
      }
      let obj = {
        remark: this.remark,
        address: this.paymentAddr.id,
        data: [],
        cart: this.cart
      };
      this.goodList.forEach(item => {
        obj.data.push({
          id: item.commodity.id,
          number: item.commodity.number,
          spec: item.commodity.spec_ids,
          coupon: item.cpId
        });
      });
      if (this.goodList[0].commodity.is_serve === 1) {
        if (!this.serviceTime) {
          this.$dialog.toast({
            mes: "请选择服务时间",
            icon: "error"
          });
          return;
        }
        obj.data[0].service_time = this.serviceTime;
        obj.data[0].coupon_id = this.usedCp.id;
        
        obj.imgFront = this.imgFront;
        obj.imgBack = this.imgBack;
      }
      if(this.$route.query.isSpell) {
        obj.isSpell = 1
        obj.active_team_id = this.$route.query.active_team_id
      }
      if(this.$route.query.isSeckill) {
        obj.isSeckill = 1
      }
      if(this.usedCp && Object.keys(this.usedCp).length) {
            obj.data[0].coupon_id = this.usedCp.id;
          }

      orderSubmit(obj).then(res => {
        if (res.status === 200) {
          console.log(res)
          // wx.miniProgram.postMessage({ order_no: res.data.data.order_no })
          // 是否使用优惠券
          
          let data = {};
          
          data.balance = res.data.data.balance;
          data.payment = res.data.data.payment;
          data.order_no = res.data.data.order_no;
          data.userPoints = res.data.data.points;
          data.points = pointCost;
          this.orderInfo = data;
          this.showPaymentMask = true;
        } else if (res.data.code === 208) {
          this.$dialog.toast({
            mes: res.data.message,
            timeout: 1000
          })
        }
      });
    },
    couponStr(item, index) {
      let usedCp = {};
      item.coupon.forEach(cp => {
        if (
          this.paymentCouponList[cp.id].usedSpecId &&
          this.paymentCouponList[cp.id].usedSpecId === item.commodity.spu_id
        ) {
          usedCp = cp;
          return;
        }
      });
      this.goodList[index].minus = Object.keys(usedCp).length
        ? usedCp.minus
        : 0;
      this.goodList[index].cpId = Object.keys(usedCp).length ? usedCp.id : 0;
      this.usedCp = usedCp
      
      return Object.keys(usedCp).length
        ? "已优惠" + usedCp.minus + "元"
        : "请选择";
    },
    orderTotalPrice() {
      let tp = 0;
      this.goodList.forEach(item => {
        let price = 0;
        if (this.isVip && this.vip_rule !== 0) {
          price -= -item.commodity.discount_price * item.commodity.number;
        } else {
          price -= -item.commodity.spe_price * item.commodity.number;
        }
        price -= -item.commodity.freight;
        price -= item.minus ? item.minus : 0;
        tp += price;
      });
      return tp > 0 ? tp : 0;
    },
    totalPrice(item) {
      let price = 0;
      if (this.isVip && this.vip_rule !== 0) {
        price -= -parseFloat(item.commodity.discount_price) * item.commodity.number ;
      } else{
        price -= -parseFloat(item.commodity.spe_price) * item.commodity.number ;
      }
      // console.log(item.minus);
      price += parseFloat(item.commodity.freight);
      // price -= item.minus ? item.minus : 0;
      return price > 0 ? price : 0;
    }
  },
  beforeRouteEnter(to, from, next) {
    // console.log(from);
    if (
      from.path.indexOf("/item-detail") === -1 &&
      from.path.indexOf("/addr-mng") === -1 &&
      from.path.indexOf("/my-coupon") === -1 &&
      from.path.indexOf("/cart") === -1 &&
      from.path.indexOf("/service-time") === -1 &&
      from.path.indexOf("/vip-protocol") === -1
    ) {
      next(vm => {
        vm.$router.go(-1);
      });
    } else {
      next();
    }
  },
  beforeRouteLeave(to, from, next) {
    if (
      to.path.indexOf("/my-coupon") === -1 &&
      to.path.indexOf("/addr") === -1 &&
      to.path.indexOf("/vip-protocol") === -1 &&
      from.path.indexOf("/service-time") === -1
    ) {
      this.clearCoupon();
      this.clearTime();
    }
    next();
  },
  created() {
    // console.log(this.$route.query.invite_code)
    if (this.$route.query.invite_code) {
      this.$router.replace({path: '/main-login', query: {invite_code: this.$route.query.invite_code}})
      return
    }
    toPayment(this.$route.query).then(res => {
      console.log(res, '???')
      if (res.status === 200) {
        
        this.goodList = res.data.data.commodity;
        this.isVip = res.data.data.level;
        this.userPoints = res.data.data.user_points;
        this.cart = res.data.data.cart ? res.data.data.cart : "";
        this.identity_e = res.data.data.identity_e;
        this.identity_v = res.data.data.identity_v;
        this.goodList.forEach(item => {
          //判断是否有vip礼包
          if (item.commodity.is_vip === 1) {
            this.hasVipGiftBag = true;
            return;
          }
        });
        if (
          res.data.data.address !== null &&
          Object.keys(this.paymentAddr).length === 0
        ) {
          this.setAddr(res.data.data.address);
        }
        if (Object.keys(this.paymentCouponList).length === 0) {
          this.couponMarking({ commodity: this.goodList });
        }
      } else if (res.data.code === 208) {
        console.log(res.data)
        this.$dialog.toast({
          mes: res.data.message,
          timeout: 1000
        })
        setTimeout(() => {
          this.$router.back()
        }, 1500)
        
      }
    });
  },
  components: {
    paymentMask
  }
};
</script>

<style lang="less" scoped>
.container {
  color: #444444;
  .id-card {
    background: #fff;
    padding: 0 3.2%;
    font-size: 0.52rem;
    .title {
      height: 2rem;
      line-height: 2rem;
    }
    .card-img {
      display: flex;
      justify-content: space-between;
      padding: 0.5rem 0 2rem;
      .card-cell {
        height: 4rem;
        width: 6.56rem;
        text-align: center;
        color: #666666;
        font-size: 0.48rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .addr-panel {
    margin: 0.48rem 3.2%;
    background: #fff;
    border-radius: 0.16rem;
    display: flex;

    .addr-icon {
      width: 1.8rem;
      background-image: url("../../assets/确认下单-填好-assets/地址.png");
      background-size: 0.84rem 0.88rem;
      background-repeat: no-repeat;
      background-position: 50% 50%;
    }

    .addr {
      width: calc(100% - 2.6rem);
      font-size: 0.64rem;
      padding: 0.4rem 0;
    }

    .addr-info {
      width: 76%;
      font-size: 0.56rem;

      .user {
        margin: 0.6rem 0 0.2rem;
        font-size: 0.64rem;

        .tel {
          color: #999999;
          font-size: 0.56rem;
          margin-left: 0.48rem;
        }
      }

      .addr-detail {
        margin: 0.5rem 0;
        color: #999999;
      }

      .default {
        font-size: 0.56rem;
        color: #f85859;
        background: rgba(248, 88, 89, 0.2);
        border-radius: 0.12rem;
        padding: 0.05rem 0.24rem;
      }
    }

    .right-btn {
      width: 0.8rem;
      background-image: url("../../assets/发视频-assets/next.png");
      background-size: 0.28rem 0.52rem;
      background-repeat: no-repeat;
      background-position: 50% 50%;
    }
  }
  .service-panel {
    margin: 0.48rem 3.2%;
    background: #fff;
    border-radius: 0.16rem;
    display: flex;
    justify-content: space-between;
    font-size: 0.64rem;
    padding: 0 0.72rem 0 0.48rem;
    .addr {
      width: 5rem;
      padding: 0.4rem 0;
    }
    .time-info {
      width: calc(100% - 6.5rem);
      text-align: right;
      color: #f85859;
      padding: 0.4rem 0;
    }
    .right-btn {
      width: 0.8rem;
      background-image: url("../../assets/发视频-assets/next.png");
      background-size: 0.28rem 0.52rem;
      background-repeat: no-repeat;
      background-position: 50% 50%;
    }
  }
  .item-panel {
    background: #fff;
    border-radius: 0.16rem;
    padding: 0 3.2%;
    margin: 0 3.2% 0.48rem;
    overflow: hidden;

    .item-info {
      display: flex;
      margin-top: 0.48rem;
      font-size: 0.56rem;
      .left {
        width: 3.2rem;
        height: 3.2rem;
        background-color: #dfdfdf;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .right {
        width: 3rem;
        text-align: right;

        .inventory {
          color: #999999;
          margin-top: 2rem;
        }
      }

      .middle {
        padding-left: 0.48rem;
        width: calc(100% - 6.2rem);

        .item-name {
          max-height: 1.5rem;
          overflow: hidden;
        }

        .item-size {
          color: #999999;
          margin-top: 1rem;
        }
      }
    }
  }

  .item-cell {
    font-size: 0.56rem;
    display: flex;
    justify-content: space-between;
    color: rgba(68, 68, 68, 1);
    min-height: 1.8rem;

    .header {
      line-height: 1.8rem;

      .vip-tag {
        background: rgba(244, 67, 73, 1);
        color: #fff;
        border-radius: 0.12rem;
        font-size: 0.4rem;
        padding: 0 0.16rem;
      }
    }

    .coupon-text {
      color: #999999;
      line-height: 1.8rem;
    }

    .postage {
      color: #666666;
      line-height: 1.8rem;
    }

    .vip-price {
      font-weight: bold;
      color: rgba(248, 88, 89, 1);
      line-height: 1.8rem;
      text-align: right;

      button {
        height: 0.96rem;
        line-height: 0.96rem;
        background: rgba(248, 88, 89, 1);
        border-radius: 0.16rem;
        color: #fff;
        border: none;
        padding: 0 0.34rem;
      }
    }

    input {
      width: 80%;
      background: none;
      border: none;
    }

    .total {
      color: #999999;
      line-height: 1.8rem;

      .price {
        color: #f85859;
      }
    }
  }

  .bottom-bar {
    position: fixed;
    width: 100%;
    left: 0;
    bottom: 0;
    height: 2rem;
    line-height: 2rem;
    text-align: right;
    background: #fff;

    .text {
      font-size: 0.56rem;
      color: #999999;

      .price {
        color: #f85859;
        font-weight: bold;
      }

      margin-right: 1.02rem;
    }

    .submit {
      border: none;
      background: rgba(0, 120, 255, 1);
      color: #fff;
      font-size: 0.64rem;
      height: 2rem;
      width: 6.5rem;
    }
  }

  .protocol {
    padding: 0.5rem 3.2%;
    line-height: 0.88rem;
    color: rgba(0, 120, 255, 1);
    font-size: 0.56rem;

    button {
      vertical-align: middle;
      width: 0.88rem;
      height: 0.88rem;
      border: 1px solid #dfdfdf;
      border-radius: 50%;
      background: none;
      overflow: hidden;
    }

    .active {
      background-image: url("../../assets/购物车-assets/xuanzhong.png");
      background-size: 100% 100%;
    }

    .protocol-name {
      text-decoration: underline;
    }
  }
}
</style>
